<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="45%"
        v-model="modleVisible"
        :title="form.id ? '编辑角色' : '新增角色'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <div class="modalContentFormTitle">基础信息</div>
            <div class="modalContentFormContent">
              <a-form-model
                ref="formRef"
                :model="form"
                :rules="rules"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 14 }"
              >
                <Input :form="form" label="角色名称" prop="name" placeholder="请输入角色名称"></Input>
                <Input :form="form" label="角色代码" prop="code" placeholder="请输入角色代码"></Input>
                <Textarea :form="form" label="备注" prop="remark" placeholder="请输入备注"></Textarea>
              </a-form-model>
            </div>
          </div>
          <div class="modalContentTree">
            <div class="modalContentTreeTitle">
              <div class="title">菜单分配</div>
            </div>
            <div class="modalContentTreeContent">
              <!-- <a-tree
                :replaceFields="{
                  title: 'name',
                  key: 'id'
                }"
                v-model="checkedKeys"
                checkable
                :expanded-keys.sync="expandedKeys"
                :tree-data="permissionsTreeArray"
              /> -->
              <typicalLeftTree
                ref="typicalLeftTree"
                :leftTreeConfig="leftTreeConfig"
                @selectionChange="selectionChange"
              ></typicalLeftTree>
            </div>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">角色列表</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit()"> 新增角色 </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button v-if="slotProps.record.isSystem !== 1" type="stop" label="删除"></Button>
              </a-popconfirm>
              <!-- 20220111z 停用角色会清空已选菜单 -->
              <!-- <Button
                v-if="slotProps.record.isSystem !== 1"
                :type="slotProps.record.isEnable === 0 ? 'start' : 'stop'"
                @click="fnStartStop(slotProps.record)"
              ></Button> -->
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
// import { disableRoleById, enableRoleById } from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import typicalLeftTree from '@/components/typicalLeftTree';
import Input from '@/components/typicalControl/Input';
import Textarea from '@/components/typicalControl/textarea';
import Button from '@/components/typicalControl/button';

import { listRoles } from '@/api/cabin';
import { userInfo } from '@/api/user';
export default {
  name: 'RoleManage',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    typicalLeftTree: typicalLeftTree,
    Input: Input,
    Button: Button,
    Textarea: Textarea,
  },
  data() {
    return {
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        name: undefined,
        code: undefined,
        isEnable: 1,
        isSystem: 0,
        remark: undefined,
        resourceId: [],
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入角色代码', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
      },
      checkedKeys: [], // 树形下拉选中的数据
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchName',
            value: '',
            label: '角色名称',
          },
          {
            type: 'input',
            prop: 'searchCode',
            value: '',
            label: '角色代码',
          },
          {
            type: 'rangeDatePicker',
            prop: 'createTime&endTime',
            value: [],
            label: '创建日期',
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '角色名称',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '角色代码',
            dataIndex: 'code',
            ellipsis: true,
          },
          {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
          },
          // {
          //   title: '状态',
          //   dataIndex: 'isEnable',
          //   width: '60px',
          //   scopedSlots: { customRender: 'isEnable' }
          // },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
            customRender: this.formatterTime,
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true,
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      // 详情左侧树组件
      leftTreeConfig: {
        isSelection: true,
        treeType: 'permissions',
        treeData: [],
      },
    };
  },
  created() {
    this.getRolePermissions(); // 获取角色权限
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    /**
     * @description: 获取角色权限
     */
    getRolePermissions() {
      userInfo().then((res) => {
        if (res.code === 200) {
          this.leftTreeConfig.treeData = res.data;
        }
      });
    },
    /**
     * [fnStartStop 启用停用方法]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    // fnStartStop(row) {
    //   this.roleLoading = true;
    //   if (row.isEnable === 1) {
    //     disableRoleById({ id: row.id })
    //       .then((res) => {
    //         this.formSuccessOperation(res);
    //       })
    //       .finally(() => {
    //         this.roleLoading = false;
    //       });
    //   } else {
    //     enableRoleById({ id: row.id })
    //       .then((res) => {
    //         this.formSuccessOperation(res);
    //       })
    //       .finally(() => {
    //         this.roleLoading = false;
    //       });
    //   }
    // },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      let params = {
        pageNum: searchParam.pageNumber + 1,
        pageSize: searchParam.pageSize,
        name: searchParam.searchName,
        code: searchParam.searchCode,
        createTime: searchParam.createTime,
        endTime: searchParam.endTime,
      };
      listRoles('/selectRoles', 'get', params)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * @description: 新增编辑角色表单提交
     */
    onSubmit() {
      if (this.form.isSystem == 1) {
        this.modleVisible = false;
        return;
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.resourceId = this.checkedKeys.map((item) => {
            return item;
          });
          // 判断是否至少选择了一个权限
          // if (this.form.resourceId.length === 0) {
          //   this.$message.error('请勾选菜单分配');
          //   return false;
          // }
          this.formButtonDisableFlag = true;
          if (this.form.id) {
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        name: undefined,
        code: undefined,
        isEnable: 1,
        isSystem: 0,
        remark: undefined,
        resourceId: [],
      };
    },

    /**
     * @description: 新增角色权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      listRoles('/insertRoles', 'post', addRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('角色添加成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 编辑角色权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      listRoles('/updateRoles', 'put', editRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [新增为空，编辑携带行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.modleVisible = true;
      this.form = this.initializationForm();
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.checkedKeys = [];
      if (row) {
        let { id, name, code, remark } = { ...row };
        this.form = { id, name, code, remark };
        this.checkedKeys = row.resourceList.map((item) => {
          return item.id;
        });
        this.form.resourceId = this.checkedKeys;
        this.$nextTick(() => {
          this.$refs.typicalLeftTree.setChecked(this.checkedKeys);
        });
      } else {
        this.$nextTick(() => {
          this.$refs.typicalLeftTree.setChecked(this.checkedKeys);
        });
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      listRoles(`/updateRoles/${roleTableRowData.id}`, 'put').then((res) => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.$refs.insideTable.updateListData();
        }
      });
    },

    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    /**
     * [selectionChange 左侧树多选变化]
     * @param  {[type]} selectedKeys [最新勾选值]
     * @return {[type]}              [description]
     */
    selectionChange(selectedKeys) {
      this.checkedKeys = selectedKeys;
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 400px;
  display: flex;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 400px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .modalContentForm {
    width: 50%;
    height: 100%;
    border-right: 1px solid #ececec;
    display: flex;
    flex-direction: column;
    .modalContentFormTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
    }
    .modalContentFormContent {
      padding: 0 0 0 20px;
      flex: 1;
    }
    .modalContentFormContent /deep/ .ant-form-item-label {
      display: inline-block;
      overflow: hidden;
      line-height: 39.9999px;
      white-space: nowrap;
      text-align: right;
      vertical-align: middle;
      width: 100px;
    }
  }
  .modalContentTree {
    width: 50%;
    height: 100%;
    max-height: 500px;
    .modalContentTreeTitle {
      width: 100%;
      height: 64px;
      display: flex;
      font-size: 16px;
      .title {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .icon {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }
    .modalContentTreeContent {
      width: 80%;
      height: 334px;
      margin: 0 auto;
    }
  }
}
/deep/ .ant-input {
  padding: 4px 6px;
}
/deep/ .ant-col .ant-col-4{
  // width: 18.666667%;
}
</style>
